<?php
/**
 * Prado Portal.
 *
 * @author Steen Rabol <steen.rabol@gmail.com>
 * @link http://www.pradoportal.dk/
 * @copyright Copyright &copy; 2006,2007,2008 Steen Rabol
 * @license http://www.pradoportal.dk
 * @version $Id: NewUserOpenId.php 425 2011-01-05 10:30:30Z steen.rabol $
 *
 */

Prado::using('Application.Common.Data.PortalUserRecord');
Prado::using('Application.Common.Data.PortalToDoRecord');
Prado::using('Application.Common.Data.PortalUserOpenIdRecord');
Prado::using('Application.Common.XMimeMail');
Prado::using('Application.Common.PortalOpenId');

class NewUserOpenId extends PortalSystemPage
{
	private $_action	= null;

	public function onInit($param)
	{
		if(!TPropertyValue::ensureBoolean($this->Application->Parameters['MultipleUser']))
			throw new PortalException(500,'newuser_registration_disallowed');

		$this->Action	= $this->Request['action'];

		if($this->IsPostBack && $this->Action === null)
		{
			$this->Visible = false;
		}
	}

	public function getAction()
	{
		return $this->_action;
	}

	public function setAction($value)
	{
		$this->_action = $value;
	}

	public function onLoad($param)
	{
		if($this->Action === null)
		{
			parent::onLoad($param);
			$this->Title = $this->Application->Parameters['SiteTitle'] . " - " . Prado::localize("Register as user");

			$this->pnlVerifyOpenId->Visible = true;
			$this->pnlVerifyOpenId->Enabled = true;

			$this->pnlNewUserOpenId->Visible	= false;
			$this->pnlNewUserOpenId->Enabled	= false;
		}

		if($this->Action === 'oidok')
		{
			$poid			= new PortalOpenId();
			$returntourl	= $this->Request->BaseUrl . $this->Service->constructUrl('System.NewUserOpenId',array('action' => 'oidcomplete'));
			$trusturl		= $this->Request->BaseUrl . '/';

			$sreg = $poid->CompleteSimpleRegistration($returntourl);
			$g = PortalUtil::getGUID();
			$this->Session->add('doreg_guid',$g);
			$urlparm = array_merge($sreg,array('action' => 'doreg','guid' => $g));
			$this->gotoPage('System.NewUserOpenId',$urlparm);
		}

		if($this->Action === 'doreg')
		{
			//Security check
			$session_guid	= $this->Session->itemAt('doreg_guid');
			$url_guid		= $this->Request['guid'];

			if($session_guid !== $url_guid)
			{
				// Possible 'hacking'...
				$this->reportError(0,Prado::localize('Something went wrong during verification of your request, please try again.'));
			}

			$this->pnlVerifyOpenId->Visible = false;
			$this->pnlVerifyOpenId->Enabled = false;

			$this->pnlNewUserOpenId->Visible	= true;
			$this->pnlNewUserOpenId->Enabled	= true;

			$this->SiteNews->Checked = true;
			$this->dlLanglist->PromptText	= Prado::localize("Select");
			$this->dlLanglist->PromptValue	= 0;
			$avlLang	=  $this->DataAccess->createCommand("select culture,name from tbllanguages where active=1")->query()->readAll();
			$this->dlLanglist->DataSource	= $avlLang;
			$this->dlLanglist->dataBind();

			$this->ok_openid_url->Text			= $this->Request['openid_url'];
			$this->Username->Text				= $this->Request['nickname'];
			$this->FullName->Text				= $this->Request['fullname'];
			$this->Email->Text					= $this->Request['email'];

			$check_lang	= strtolower($this->Request['language']);
			foreach($avlLang as $al)
			{
				if($al['culture'] === $check_lang)
				{
					$this->dlLanglist->SelectedValue	= $check_lang;
					break;
				}
			}
		}
	}

	public function checkUsername($sender,$param)
	{
		$username	= $this->Username->Text;

		$id = $this->DataAccess->createCommand("select * from tblusers where name='$username'")->queryRow();

		if($id)
		{
			$param->IsValid = false;
		}
		else
		{
			$param->IsValid = true;
		}
	}

	public function checkEmail($sender,$param)
	{
		$email = strtolower($this->Email->Text);
		$id = $this->DataAccess->createCommand("select * from tblusers where email='$email'")->queryRow();

		if($id)
		{
			$this->reportError(0,Prado::localize("Your email address '{0}' is allready in use.<br>Login and attach your OpenId to your account."));
		}
		else
		{
			$param->IsValid = true;
		}
	}

	public function createUser($sender,$param)
	{
		if($this->IsValid)
		{
			$nu = new PortalUserRecord();
			$nu->name		= $this->Username->Text;
			$nu->full_name	= $this->FullName->Text;
			$nu->role		= $this->Application->Parameters['NewUserRole'];
			$psw = $this->Application->Parameters['OpenIdPassword'];//PortalUtil::MakePassword();
			$nu->password	= hash("sha256",$psw);
			$nu->vcode		= PortalUtil::getGUID();
			$nu->email		= $this->Email->Text;
			$nu->reg_time	= time();
			$nu->status		= TPropertyValue::ensureBoolean($this->Application->Parameters['AccountApproval']) ? 2 : 0;
			$nu->sitenews	= TPropertyValue::ensureInteger($this->SiteNews->Checked);
			$nu->culture	= $this->dlLanglist->SelectedValue;
			$nu->save();

			// Attach OpenId
			//Strip http://
			$openid_url = str_replace("http://","",$this->ok_openid_url->Text);
			$openid_url = str_replace("https://","",$openid_url);
			PortalUserOpenIdRecord::AttachOpenID($openid_url, $nu->id);

			// Create an todo or send email ?
			$nuaction = TPropertyValue::ensureBoolean($this->Application->Parameters['NewAccountAction']);
			switch($nuaction)
			{
				case 0: //nop
					break;

				case 1: //Create todo
					$this->CreateToDo($this->Username->Text);
					break;

				case 2: // Send admin email
					$this->SendAdminMail($this->Username->Text);
					break;

				case 3: // Send admin email and create todo
					$this->CreateToDo($this->Username->Text);
					$this->SendAdminMail($this->Username->Text);
					break;
			}

			if(TPropertyValue::ensureBoolean($this->Application->Parameters['AccountApproval']))
			{
				$this->gotoPage('System.NewUserCreated');
			}
			else
			{
				// Log user in
				$authManager=$this->Application->getModule('auth');
				if(!$authManager->login($nu->name,$psw))
				{
					$this->reportError(0,"Strange... " . $nu->name . " with " . $nu->password . " could nut be logged in...");
				}
				$this->gotoDefaultPage();
			}
		}
	}

	private function CreateToDo($username)
	{
		$todo = new PortalToDoRecord();
		$todo->title		= Prado::localize('New user created');
		$todo->description	= Prado::localize('New user created with name {0}',array($username));
		$todo->created		= time();
		$todo->deadline		= time() + (60*60*60*24);
		$todo->priority		= 1;
		$todo->assignedto	= 1;
		$todo->assignedby	= 1;
		$todo->createdby	= 1;
		$todo->save();
	}

	private function SendAdminMail($username)
	{
		$to_email	= $this->Application->Parameters['AdminEmail'];
		$to_name	= $this->Application->Parameters['SiteOwner'];
		$xMail = new XMimeMail();
		$xMail->setCharset('iso-8859-1');
		$xMail->setHtmlBody(Prado::localize('New user created with name {0}',array($username)),'');
		$params['html_encoding'] = 'quoted-printable';
		$params['text_encoding'] = 'quoted-printable';
		$params['text_wrap'] = 998;
		$xMail->prepare($params);

		try
		{
			$xMail->send($to_name, $to_email, "Prado portal", $this->Application->Parameters['AdminEmail'], Prado::localize('New user created'));
		}
		catch(Exception $e)
		{
			$this->reportError(0, $e->getMessage());
		}
	}

	public function VerifyButtonClicked($sender,$param)
	{
		if($this->Page->IsValid)
		{
			$this->Visible = false;
			$this->pnlVerifyOpenId->Visible	= false;
			$this->pnlVerifyOpenId->Enabled	= false;

			$poid			= new PortalOpenId();
			$returntourl	= $this->Request->BaseUrl . $this->Service->constructUrl('System.NewUserOpenId',array('action' => 'oidok'));
			$trusturl		=  $this->Request->BaseUrl . '/';
			$poid->BeginSimpleRegistration($this->openid_url->Text, $trusturl, $returntourl);
		}
	}

	public function checkOpenIdUrl($sender,$param)
	{
		$uid = PortalUserOpenIdRecord::GetUserId($param->Value);

		if($uid == 0)
		{
			$param->IsValid = true;
		}
		else
		{
			$param->IsValid = false;
		}
	}
}
?>